package cn.invengo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

@Controller
public class MainController {
    @Autowired
    private SimpMessagingTemplate template;

    @Autowired
    private SessionRegistry sessionRegistry;

    @RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
    public String index(Principal principal, Model model) {
        String currentUser = principal.getName();
        model.addAttribute("name", currentUser);
        List<String> users = new ArrayList<>();

        final List<Object> allObjectList = sessionRegistry.getAllPrincipals();
        for (Object obj : allObjectList) {
            if (obj instanceof User) {
                User user = (User) obj;
                String username = user.getUsername();
                if (!username.equals(currentUser)) {
                    users.add(username);
                }
            }
        }
        model.addAttribute("users", users);
        return "index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(@RequestParam(value = "error", required = false) String error,
                              @RequestParam(value = "logout", required = false) String logout,
                              Model model) {
        if (error != null) {
            model.addAttribute("error", "Invalid username or password");
        }
        if (logout != null) {
            model.addAttribute("msg", "Logout successfully");
        }
        return "login";
    }

    /**
     * Get all login session user
     * @param message
     * @param from
     * @param to
     * @return
     */
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public String send(@RequestParam(value = "message")String message,
                     @RequestParam(value = "from") String from,
                     @RequestParam(value = "to") String to) {
        template.convertAndSendToUser(to, "/queue/chat", message);
        return "redirect:/";
    }
}
